package com.tengju.bff.interfaces.manage.crm.activity;

import com.tengju.bff.interfaces.manage.crm.activity.facade.ActivityTargetManageFacade;
import com.tengju.bff.interfaces.manage.crm.activity.form.ActivityTargetSaveForm;
import com.tengju.bff.interfaces.manage.crm.activity.vo.ActivityDetailVO;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.servlet.ManageEntrance;
import com.tengju.motivation.application.shared.ApplicationException;
import com.tengju.motivation.domain.model.activity.ActivityId;
import com.tengju.motivation.domain.model.activity.ActivityRepository;
import com.tengju.support.domain.annotation.BizLog;
import com.tengju.support.domain.annotation.BizLogSysName;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.tengju.user.domain.shared.ResultCodeEnum.BIZ_ERROR;
import static com.tengju.user.domain.shared.ResultCodeEnum.SYS_EXCEPTION;

@Validated
@RestController
@Api(tags = "组织管理-销售活动管理")
@RequestMapping(value = "manage/crm/activity/target/")
@Slf4j
@ManageEntrance
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class ActivityTargetController {

    private final ActivityTargetManageFacade activityTargetManageFacade;
    private final ActivityRepository activityRepository;


    @ApiOperation(value = "活动目标是否存在", notes = "活动目标是否存在")
    @GetMapping(value = "/exist", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<Boolean> exist(@RequestParam("activityId") Long activityId) {
        return ApiResponse.newSuccess(activityRepository.countTarget(new ActivityId(activityId)) > 0);
    }

    @ApiOperation(value = "活动目标详情", notes = "活动目标详情")
    @GetMapping(value = "/detail", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<ActivityDetailVO> detail(@RequestParam("activityId") Long activityId) {
        return activityTargetManageFacade.detail(new ActivityId(activityId));
    }

    @BizLog(sysName = BizLogSysName.TENGJU_ACTIVITY_TARGET_MANAGE)
    @ApiOperation(value = "活动目标保存", notes = "活动目标保存")
    @PostMapping(value = "/save", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<Void> save(@RequestBody ActivityTargetSaveForm form) {
        try {
            return activityTargetManageFacade.save(form);
        }catch (ApplicationException e){
            return ApiResponse.newFailure(BIZ_ERROR.getCode(), e.getMessage());
        }catch (Exception e){
            log.error("保存失败", e);
            return ApiResponse.newFailure(SYS_EXCEPTION.getCode(), e.getMessage());
        }
    }


}
